package com.mgfireworks.mgplatform.mgadmin.user;

import cn.hn.java.summer.db.BaseDao;
import cn.hn.java.summer.db.multiple.DataSource1;
import cn.hn.java.summer.exception.BusinessException;
import cn.hn.java.summer.utils.codec.Coder;
import com.mgfireworks.mgplatform.mgadmin.comm.IncreaseIdService;
import com.mgfireworks.mgplatform.mgadmin.sys.OrganizationService;
import com.mgfireworks.mgplatform.mgadmin.sys.model.Organization;
import com.mgfireworks.mgplatform.mgadmin.user.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 
 * @author nap
 * 20161015-10:19:48
 * 用户业务类
 */
@Service
public class UserService extends BaseDao<DataSource1>{
	@Autowired
	IncreaseIdService increaseIdService;
	@Autowired
	OrganizationService organizationService;

	/**
	 * 取用户列表
	 * @return
	 */
	public List<User> getUsers(User p){
		return list("getUsers",User.class,p);
	}

	/**
	 * 添加用户
	 */
	public void addUser(User p){
		p.setUserId(increaseIdService.getNewUserId());
		p.setUserPwd(Coder.encryptMD5(p.getUserPwd()));
		update("addUser",p);
	}
	
	/**
	 * 修改用户
	 */
	public void editUser(User p){
		p.setUserPwd(Coder.encryptMD5(p.getUserPwd()));
		update("editUser",p);
	}
	
	/**
	 * 删除用户
	 */
	public void delUser(User p){
		update("delUser",p);
	}
	
	/**
	 * 取用户
	 */
	public User getUser(User p){
		return get("getUser",User.class,p);
	}
	
	/**
	 * 登录
	 * @param u
	 * @return
	 * @throws BusinessException
	 */
	public User login(User u) throws BusinessException{
		User targetUser= getUser(new User(u.getUserAccount()));
		if(
			targetUser==null || 
			!Coder.encryptMD5(u.getUserPwd()).equals(targetUser.getUserPwd())
		){
			throw new BusinessException("登录失败,账户或密码错误！");
		}

		//取出用户所在机构的区域编号
        Organization org= organizationService.getOrganization(new Organization(targetUser.getOrgId()));
        targetUser.setAreaId(org.getAreaId());
		return targetUser;
	}

	public static void main(String[] args) {
		System.out.println(Coder.encryptMD5("admin"));
	}
}